To encapsulate business logic, services are introduced. Services are used in Angular applications for data or logic that is not associated with any specific view.
Create Command
ng generate service apiService
How do services work?
- The @Injectable() decorator defines a class as a service in Angular and informs Angular to inject it into a component as a dependency.
- Services are instantiated only once in the application.
- It contains methods that maintain data throughout the life of an application.
- This data does not get refreshed and is available all the time. We can use services to store some temporary data while implementing a web application.
- Initiate instance of service in component and assign value to be used in another component.
- To register services as a part of the component, we have to specify it in the providers’ array of the module.
Example
header.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class HeaderService {
featureHeading: string;
constructor() {}
}
myFirstComponent.ts
ngOnInit(): void {
this.featureHeadingService.featureHeading = 'My favourite super heroes!;
}